import { createPinia } from "pinia";
import type { PiniaPluginContext } from "pinia";
const pinia = createPinia();
const sessionStoreIds = ["esServerIndexField"];
const breakLocalStoreIds: Array<string> = [];
// 插件 有几个仓库就执行几次
pinia.use((context: PiniaPluginContext) => {
    if (breakLocalStoreIds.includes(context.store.$id)) {
        return;
    }
    // 获取当前的仓库状态
    const currentState = JSON.parse(localStorage.getItem(context.store.$id) || sessionStorage.getItem(context.store.$id) || "{}");
    if (Object.keys(currentState).length) {
        // 更新数据 同步效果
        context.store.$patch(currentState);
    }
    context.store.$subscribe(
        (mutation, state) => {
            if (sessionStoreIds.includes(mutation.storeId)) {
                sessionStorage.setItem(mutation.storeId, JSON.stringify(state));
            } else {
                // 每次state发生变化时 将数据同步到本地存储
                localStorage.setItem(mutation.storeId, JSON.stringify(state));
            }
        },
        {
            detached: true
        }
    );
    
});

export default pinia;
